from flask import Blueprint,jsonify,request
from redisss import r
from db import db1
import random
import json
from werkzeug.security import generate_password_hash,check_password_hash


bp_user = Blueprint('user',__name__)


@bp_user.route('/send',methods=['POST','GET'])
def user():
    if request.method == 'GET':
        mobile = request.args.get('mobile')
        codes = str(random.randint(1000,9999))
        r.set_str(mobile,codes,60)
        return jsonify({'code':200,'codes':codes})

@bp_user.route('/regi',methods=['POST'])
def regi():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        codes = r.get_str(data['mobile'])
        if not codes:
            return jsonify({'code':20010,'mes':'验证码不存在'})
        if codes != data['codes']:
            return jsonify({'code':20011,'mes':'验证码错误'})

        sql = 'select id from user where mobile = "%s"'%(data['mobile'])
        res = db1.findone(sql)
        if res:
            return jsonify({'code':20012,'mes':'手机号已存在'})
        sql = 'insert into user values (0,"%s","%s","%s")'%(data['name'],data['mobile'],generate_password_hash(data['password']))
        db1.insert(sql)
        return jsonify({'code':200})


@bp_user.route('/login',methods=['POST','GET'])
def login():
    if request.method == 'POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = 'select * from user where mobile = "%s"'%(data['mobile'])
        res = db1.findone(sql)
        if res:
            if check_password_hash(res['password'],data['password']):
                return jsonify({'code':200,'userid':res['id'],'name':res['name']})
            else:
                return jsonify({'code':20015,'mes':'密码错误'})
        else:
            return jsonify({'code':20016,'mes':'用户名不存在'})
    elif request.method == 'GET':
        sql = 'select name from user order by id desc '
        res = db1.findall(sql)
        return jsonify({'code':200,'list':res})




